<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="成果标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入成果标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:fruit:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:fruit:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:fruit:remove']"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="fruitList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="index" label="序号" align="center" width="70" />
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="成果标题" align="center" prop="title" />
      <el-table-column label="成果图片" align="center">
        <template #default="scope">
          <el-button type="primary" link @click="handleSeeQrCode(scope.row)"
            >查看</el-button
          >
        </template>
      </el-table-column>
      <el-table-column
        label="超时时间"
        align="center"
        prop="overTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.overTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:fruit:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:fruit:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <ShowQrCode v-model:visible="showQrCode" :value="qrCodeId"></ShowQrCode>
    <!-- 添加或修改展现管理对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="fruitRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="成果标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入成果标题" />
        </el-form-item>
        <el-form-item label="成果图片" prop="image">
          <ImageUpload v-model="imageList" />
        </el-form-item>
        <el-form-item label="成果介绍" prop="introduction">
          <editor v-model="form.introduction" :min-height="192" />
        </el-form-item>
        <el-form-item label="超时时间" prop="overTime">
          <el-date-picker
            clearable
            v-model="form.overTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择超时时间"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Fruit">
import {
  listFruit,
  getFruit,
  delFruit,
  addFruit,
  updateFruit,
} from "@/api/system/fruit";
import ShowQrCode from "./components/showQrCode";
const { proxy } = getCurrentInstance();

const fruitList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
//
const imageList = ref([]);
const showQrCode = ref(false);
const qrCodeId = ref("");
const validate = (rule, value, callback) => {
  if (removeHTMLTag(value) === '') {
    callback(new Error('成果简介不能为空'))
  }  else {
    callback()
  }
}
function removeHTMLTag(str) {
    str = str.replace(/<\/?[^>]*>/g, '') // 去除HTML tag
    str = str.replace(/[ | ]*\n/g, '\n') // 去除行尾空白
    str = str.replace(/\n[\s| | ]*\r/g,'\n'); //去除多余空行
    str = str.replace(/ /ig, '') // 去掉
    const arrEntities = { 'lt': '<', 'gt': '>', 'nbsp': ' ', 'amp': '&', 'quot': '"' } // 转义符换成普通字符
    str = str.replace(/&(lt|gt|nbsp|amp|quot);/ig, function(all, t) { return arrEntities[t] })
    return str
  }
const data = reactive({
  form: { },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: null,
  },
  rules: {
    title: [
      { required: true, message: "成果标题不能为空", trigger: "blur" },
      {
        min: 2,
        max: 20,
        message: "成果标题长度必须介于 2 和 20 之间",
        trigger: "blur",
      },
    ],
    introduction: [
      { validator: validate, trigger: "change" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询展现管理列表 */
function getList() {
  loading.value = true;
  listFruit(queryParams.value).then((response) => {
    fruitList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    fruitId: null,
    title: null,
    introduction: null,
    overTime: null,
  };
  imageList.value = [];
  proxy.resetForm("fruitRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}
// 查看二维码
const handleSeeQrCode = (item) => {
  console.log("🚀 ~ file: index.vue:158 ~ handleSeeQrCode ~ item:", item);
  qrCodeId.value = item.fruitId;
  showQrCode.value = true;
};
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.fruitId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加展现管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _fruitId = row.fruitId || ids.value;
  getFruit(_fruitId).then((response) => {
    console.log("🚀 ~ file: index.vue:177 ~ getFruit ~ response:", response);
    form.value.fruitId = response.data.fruitId;
    form.value.title = response.data.title;
    form.value.introduction = response.data.introduction;
    form.value.overTime = response.data.overTime;
    imageList.value = response.data.fileInfos.map((res) => {
      return { name: res.originalFilename, url: res.url, fileId: res.fileId };
    });
    open.value = true;
    title.value = "修改展现管理";
  });
}

/** 提交按钮 */
function submitForm() {
  console.log(form.value, imageList.value);
  proxy.$refs["fruitRef"].validate((valid) => {
    if (valid) {
      const params = JSON.parse(JSON.stringify(form.value));
      params.fileIds = imageList.value.map((i) => i.fileId);
      if (params.fruitId != null) {
        updateFruit(params).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addFruit(params).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _fruitIds = row.fruitId || ids.value;
  proxy.$modal
    .confirm('是否确认删除展现管理编号为"' + _fruitIds + '"的数据项？')
    .then(function () {
      return delFruit(_fruitIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/fruit/export",
    {
      ...queryParams.value,
    },
    `fruit_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>
